package com.junyu.interceptor;

import com.alibaba.fastjson.JSON;
import com.junyu.common.ResultCodeEnum;
import com.junyu.exception.LoginException;
import com.junyu.pojo.entity.User;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * 登录拦截器
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 拦截器执行之前
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //放行预检请求
        String method = request.getMethod();
        if ("OPTIONS".equals(method.toUpperCase())) {
            return true;
        }
        System.out.println(request);
        //获取token
        String token = request.getHeader("token");
        //判断token是否为空
        if (StringUtils.isEmpty(token)) {
            throw new LoginException(ResultCodeEnum.USER_NOT_LOGIN);
        }
        //查询redis缓存用户信息
        String json = redisTemplate.opsForValue().get("user:login:" + token);
        //判断用户信息是否为空
        if (StringUtils.isEmpty(json)) {
            throw new LoginException(ResultCodeEnum.USER_NOT_LOGIN);
        }
        //将用户信息存入ThreadLocal
        ThreadLocalUtil.threadLocal.set(JSON.parseObject(json, User.class));
        return true;
    }

    /**
     * 拦截器执行之后
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //删除ThreadLocal中的用户信息
        ThreadLocalUtil.threadLocal.remove();
    }
}
